# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


#  持久化数据的位置    csv   mysql  自定义
class TpycarPipeline:
    def process_item(self, item, spider):
        return item


# 将数据写入mysql数据库   setting   注册管道文件
class MysqlPipeline:
    def open_spider(self, spider):
        """程序启动时执行一次"""
        self.connection = pymysql.connect(host='localhost', port=3306, user='root',
                                          passwd='root', db='python2511', charset='utf8')
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        """数据持久化操作"""
        str_sql = "INSERT INTO `python2511`.`car`(`type`, `brand`, `rank`, `price`) VALUES (%s, %s, %s, %s)"
        self.cursor.execute(str_sql, [item['type'], item['brand'], item['rank'], item['price']])
        self.connection.commit()
        return item

    def close_spider(self, spider):
        """程序结束时执行  释放资源"""
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()
